<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/3/16 0016
 * Time: 17:27
 */
namespace app\admin\controller;
use app\models\Models;

class Business extends Check {
    /**
     * 商家列表
     * @return \think\response\View
     */
    public function businessList(){
        $get = input('param.');
        $admin = new Models('admin');
        $type = new Models('businessType');
        $search = search($get,'a.username,b.name','a.create_time','a.status');
        $where = $search['condition'].' and c.group_id = '.Models::GROUP_BUSINESS;
        $join = [
            ['business b','a.id = b.id','left'],
            ['auth_group_access c','a.id = c.uid','left'],
        ];
        $field = "a.id,a.username,a.status,a.create_time,b.name,b.amount,b.fans_num,b.order_num,b.sort,b.location";
        $list = $admin->_page($where,$field,'b.sort desc,a.id desc',$join,$get['page'],15,$get);
        $business_type = $type->_select(['status'=>Models::STATUS_ON]);
        return view('businessList',['list'=>$list->items(),'page'=>$list->render(),'display'=>$search['display'],'type'=>$business_type]);
    }

    /**
     * 添加商家
     * @return array|\think\response\View
     */
    public function businessAdd(){
        if(request()->isPost()){
            $post   = input('param.');
            $admin  = new Models('admin');
            $access = new Models('auth_group_access');
            $business = new Models('business');
            try{
                // 场景验证
                $validate = self::validate($post,'Admin.adminAdd');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                // 添加管理员
                $add = [
                    'username'    => $post['username'],
                    'password'    => password_hash($post['password'],true),
                    'status'      => Models::STATUS_NOT_ACTIVE,
                    'create_time' => time()
                ];
                $admin->startTrans();
                $uid = $admin->_add($add);
                // 关系表添加记录
                $bool = $access->_add(['uid'=>$uid,'group_id'=>Models::GROUP_BUSINESS]);
                // 添加商家
                $data = [
                    'id'         => $uid,
                    'name'       => $post['name'],
                    'type_id'    => $post['type_id'],
                    'background' => upload('background')[0],
                    'video'      => uploadVideo('video'),
                    'descrip'    => $post['descrip'],
                    'lng'        => $post['lng'],
                    'lat'        => $post['lat'],
                    'location'   => $post['location']
                ];
                $bool2 = $business->_add($data);
                // 添加操作日志
                $log  = self::addLog('添加管理员-'.$post['username']);
                if(!$uid || false === $bool || false === $bool2 || !$log){
                    $admin->rollback();
                    throw new \LogicException('操作失败',1010);
                }
            }catch(\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            $admin->commit();
            return self::formatSuccessResult();
        }
        $type = new Models('businessType');
        $business_type = $type->_select(['status'=>Models::STATUS_ON]);
        return view('businessAdd',['type'=>$business_type]);
    }

    /**
     * 修改信息
     * @return array|\think\response\View
     */
    public function businessSave(){
        $business = new Models('business');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                $data = [
                    'id'       => $post['id'],
                    'name'     => $post['name'],
                    'type_id'  => $post['type_id'],
                    'descrip'  => $post['descrip'],
                    'lng'      => $post['lng'],
                    'lat'      => $post['lat'],
                    'location' => $post['location']
                ];
                if($_FILES['image']){
                    $data['background'] = upload('background')[0];
                }
                if($_FILES['file']){
                    $data['video'] = uploadVideo('video');
                }
                $bool = $business->_save($data);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $type = new Models('businessType');
        $config = self::getConfig();
        $info = $business->_find(['id'=>$get['id']]);
        $info['background'] = $config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'background'. DS .'s'.$info['background'];
        $business_type = $type->_select(['status'=>Models::STATUS_ON]);
        return view('businessSave',['info'=>$info,'type'=>$business_type]);
    }

    /**
     * 详情
     * @return \think\response\View
     */
    public function businessShow(){
        $get = input('param.');
        $admin = new Models('admin');
        $config = self::getConfig();
        $join = [
            ['business b','a.id = b.id','left'],
            ['business_type c','b.type_id = c.id','left'],
        ];
        $field = 'a.id,a.username,a.status,a.create_time,b.name,b.location,b.background,b.amount,b.descrip,b.order_num,b.fans_num,c.name type_name';
        $info = $admin->joinOne($join,['a.id'=>$get['id']],$field);
        $info['background'] = $config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'background'. DS .'s'.$info['background'];
        return view('businessShow',['info'=>$info]);
    }

    /**
     * 排序
     * @return array|\think\response\View
     */
    public function sort(){
        $business = new Models('business');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                $bool = $business->setValue(['id'=>$post['id']],['sort'=>$post['sort']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $sort = $business->getValue(['id'=>$get['id']],'sort');
        return view('sort',['sort'=>$sort]);
    }

    /**
     * 上传
     * @return array|\think\response\View
     */
    public function image(){
        $business = new Models('business');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                if($_FILES){
                    $path = upload('live');
                    $bool = $business->_save(['id'=>$post['id'],'image'=>json_encode($path)]);
                    if(false === $bool){
                        throw new \LogicException('操作失败',1010);
                    }
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $images = $business->getValue(['id'=>$get['id']],'image');
        $info['image'] = empty($images) ? '' : array_map([$this,'arrayMapLive'],json_decode($images,true));
        $info['id'] = $get['id'];
        return view('image',['info'=>$info]);
    }

    /**
     * 提成
     * @return array|\think\response\View
     */
    public function royalty(){
        $account = new Models('account');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                $bool = $account->setValue(['id'=>$post['id']],['sales_royalty'=>$post['royalty']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $royalty = $account->getValue(['uid'=>$get['id']],'sales_royalty');
        return view('royalty',['royalty'=>$royalty]);
    }

    /**
     * 指标
     * @return array|\think\response\View
     */
    public function target(){
        $account = new Models('account');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                $bool = $account->setValue(['id'=>$post['id']],['sales_target'=>$post['target']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $target = $account->getValue(['uid'=>$get['id']],'sales_target');
        return view('target',['target'=>$target]);
    }

    /**
     * 启用
     * @return array
     */
    public function start(){
        if(request()->isAjax()){
            $post = input('param.');
            $admin = new Models('admin');
            try{
                $bool = $admin->setValue(['id'=>$post['id']],['status'=>Models::STATUS_ON]);
                if(!$bool){
                    throw new \Exception('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 停用
     * @return array
     */
    public function stop(){
        if(request()->isAjax()){
            $post = input('param.');
            $admin = new Models('admin');
            try{
                $bool = $admin->setValue(['id'=>$post['id']],['status'=>Models::STATUS_OFF]);
                if(!$bool){
                    throw new \Exception('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 商家用户列表
     * @return \think\response\View
     */
    public function userList(){
        $id = cookie('join_login');
        $get = input('param.');
        $user = new Models('user');
        $type = new Models('userType');
        // 条件查询
        $search = search($get,'a.username,a.nickname','a.create_time','a.status');
        $where  = $search['condition'].' and a.up_id = '.$id;
        // 根据用户类型查询
        if($get['type_id']){
            $where .= ' and a.type_id = '.$get['type_id'];
            $search['display']['type_id'] = $get['type_id'];
        }
        $join   = [
            ['user_type b','a.type_id = b.id','left'],
            ['account c','a.id = c.uid','left'],
            ['business d','a.up_id = d.id','left']
        ];
        $field  = "a.*,b.name,c.balance,c.coin_balance,c.sales_target,((c.sales_month/c.sales_target)*100) percent,c.sales_royalty";
        $list = $user->_page($where,$field,'a.id desc',$join,$get['page'],15,$get);
        $userType = $type->_select(['status'=>Models::STATUS_ON,'id'=>['<>',Models::USER_TYPE_NORMAL]]);
        return view('userList',['list'=>$list->items(),'page'=>$list->render(),'display'=>$search['display'],'type'=>$userType]);
    }

    /**
     * 商家添加用户
     * @return array|\think\response\View
     */
    public function userAdd(){
        if(request()->isAjax()){
            $id = cookie('join_login');
            $post = input('param.');
            $user = new Models('user');
            $account = new Models('account');
            try{
                // 添加场景验证
                $validate = $this->validate($post,'User.businessAdd');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                $post['up_id'] = $id;
                $post['sales_target'] = empty($post['sales_target']) ? '0' : $post['sales_target'];
                $post['password'] = password_hash('123456',true);
                $post['create_time'] = time();
                $uid = $user->_add($post);
                if(!$uid){
                    throw new \LogicException('操作失败',1010);
                }
                $bool = $account->_add(['uid'=>$uid]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $type  = new Models('userType');
        // 用户类型列表
        $user_type = $type->_select(['status'=>Models::STATUS_ON,'id'=>['<>',Models::USER_TYPE_NORMAL]]);
        return view('userAdd',['type'=>$user_type]);
    }

    /**
     * 商家修改用户
     * @return array|\think\response\View
     */
    public function userSave(){
        $user = new Models('user');
        if(request()->isAjax()){
            $id = cookie('join_login');
            $post = input('param.');
            try{
                // 添加场景验证
                $validate = $this->validate($post,'User.businessSave');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                $post['up_id'] = $post['type_id'] == Models::USER_TYPE_NORMAL ? 0 : $id;
                $bool = $user->_save($post);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get   = input('param.');
        $type  = new Models('userType');
        $admin = new Models('admin');
        $info  = $user->_find($get['id']);
        // 用户类型列表
        $user_type = $type->_select(['status'=>Models::STATUS_ON]);
        // 商家列表
        $business  = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON],'a.id,b.name');
        return view('userSave',['type'=>$user_type,'info'=>$info,'business'=>$business]);
    }
}